package com.hunan.api.catv.service.biz.openApi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hunan.api.catv.entity.CodeResult;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.dto.ExternalPushDTO;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jiang zhuan
 * @version 1.0
 * @description 描述
 * @date 2020/12/15 0015
 * @package com.hunan.api.catv.service.biz.openApi
 * @company 湖南有线
 */
@Service
public class OpenApiBiz extends ResultService {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${openapi.aes.key}")
    private String key;

    @Autowired
    SystemDictBiz systemDictBiz;

    public CodeResult cdnCheck(String randomCheckCode) {
//        AES aes = new AES(key.getBytes(CharsetUtil.CHARSET_UTF_8));
//        randomCheckCode=  URLDecoder.decode(randomCheckCode, CharsetUtil.CHARSET_UTF_8);
//        randomCheckCode = aes.decryptStr(randomCheckCode);
        Object streamRandomkey = redisUtils.get("StreamRandomkey-" + randomCheckCode);
        if (!ObjectUtils.isEmpty(streamRandomkey)) {
            redisUtils.del("StreamRandomkey-" + randomCheckCode);
            return buildOKCode();
        }
        return buildFailCode("0001", "校验失败");
    }

    public ServiceResult externalPush(ExternalPushDTO externalPushDTO) {
        if (externalPushDTO.getType() == null) {
            externalPushDTO.setType(0);
        }
        if (externalPushDTO.getDestination() == null) {
            externalPushDTO.setDestination(0);
        }
        String externalPushUrl = systemDictBiz.getStringByKey("smartFamily_InterSystemPushUrl");
        String result = postHttp(externalPushUrl, externalPushDTO);
        if (StringUtils.isNotBlank(result) && getResultState(result)) {
            return buildOK(true);
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return buildFail(StringUtils.isNotBlank(jsonObject.getStr("m")) ? jsonObject.getStr("m") : "发送失败");
    }


    /**
     * 工程互相调用http/post请求
     *
     * @param url
     * @param params
     * @param <T>
     * @return
     */
    public <T> String postHttp(String url, T params) {
        Map<String, String> headers = new HashMap<>();
        headers.put("c", "3");
        headers.put("v", "1");
//        Map<String, Object> paramMap = BeanUtil.beanToMap(params);
        String sign = "e4277c43769c612644091d03ded6aa48";
        headers.put("sign", sign);
        HttpRequest httpRequest = HttpUtil.createPost(url);
        String postBody = GsonUtils.toJson(params);
        httpRequest.addHeaders(headers);
        httpRequest.body(postBody);
        HttpResponse response = httpRequest.execute();
        return response.body();
    }

    /**
     * 获取app工程默认返回结构data数据
     *
     * @param tClass
     * @param result
     * @param <T>
     * @return
     */
    public <T> T getResultData(Class<T> tClass, String result) {
        try {
            Map<String, Object> resultMap = GsonUtils.fromJson(result, Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("d");
            if (dataMap != null && dataMap.size() > 0) {
                return BeanUtil.toBeanIgnoreError(dataMap.get("data"), tClass);
            }
            return tClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e2) {
            throw new IllegalArgumentException("Can not instance class!", e2);
        } catch (Exception e) {
            log.info("GSON解析用户信息异常", e);
            try {
                return tClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e1) {
                throw new IllegalArgumentException("Can not instance class!", e1);
            }
        }
    }

    public <T> T getResultDataV2(T entity, String result) {
        try {
            Map<String, Object> resultMap = GsonUtils.fromJson(result, Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("d");
            if (dataMap != null && dataMap.size() > 0) {
                return (T) BeanUtil.toBeanIgnoreError(dataMap.get("data"), entity.getClass());
            }
            return entity;
        } catch (Exception e) {
            log.info("GSON解析用户信息异常", e);
            return entity;
        }
    }

    /**
     * 判断用户相关http请求是否成功
     *
     * @param result
     * @return
     */
    public boolean getResultState(String result) {
        try {
            Map<String, Object> resultMap = GsonUtils.fromJson(result, Map.class);
            Number code = (Number) resultMap.get("c");
            if (code.intValue() == 200) {
                Map<String, Object> data = (Map<String, Object>) resultMap.get("d");
                if (data != null && data.size() > 0) {
                    return (Boolean) data.get("status");
                }
            }
            return false;
        } catch (Exception e) {
            log.info("获取自服务请求状态异常", e);
            return false;
        }
    }

}
